//
//  NovelContentViewController.m
//  JianChaRiBao
//
//  Created by Changxy on 13-5-30.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//
#define IMAGEHIGHT self.view.bounds.size.height

#import "NovelContentViewController.h"
#import "DataRequest.h"
@interface NovelContentViewController ()

@end

@implementation NovelContentViewController
{
    BOOL isShowStatus;
}
@synthesize idStr = _idStr;
@synthesize desStr = _desStr;
@synthesize mDict = _mDict;
@synthesize itemID = _itemID;
-(void)dealloc{    
    [mWebView release];
    [currView release];
    [topView release];
    [mWindow release];
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (id)init
{
    self = [super init];
    if (self) {

    }
    return self;
}
-(id)initDict:(NSDictionary *)dict itemID:(NSString *)itemID{
    self = [super init];
    if (self) {
        shouldSwipeBack = YES;
        needSwipNext = YES;
        self.mDict = dict;
        self.idStr = [dict objectForKey:@"nc_id"];
        self.itemID = itemID;
    }
    return self;
}
-(void)swipeLeft{
    [self loadArticleAtIndex:self.currentIndex + 1];
}

- (void)loadArticleAtIndex:(int)index
{
    if (index >= self.contentArray.count) {
        ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"已经是最后一篇"]autorelease];
        [abp show];
        return;
    }

    self.currentIndex = index;
    self.mDict = [self.contentArray objectAtIndex:index];
    self.idStr = [self.mDict objectForKey:@"nc_id"];
    titlelabel.text = [self.mDict objectForKey:@"subject"];
    
    [self getData];
    [self addNovleRead];
    
    if (self.currentIndex > 0) {
        NSDictionary *dic = [self.contentArray objectAtIndex:self.currentIndex - 1];
        topTintLabel.text = [dic objectForKey:@"subject"];
    }
    else {
        topTintLabel.text = @"已经是第一篇";
    }
    if (self.currentIndex < self.contentArray.count - 1) {
        NSDictionary *dic = [self.contentArray objectAtIndex:self.currentIndex + 1];
        bottomTintLabel.text = [dic objectForKey:@"subject"];
    }
    else {
        bottomTintLabel.text = @"已经是最后一篇";
    }
}

-(void)loadView{
    [super loadView];
    topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
    [self.view addSubview:topView];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView * topbarImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
    topbarImage.userInteractionEnabled = YES;
    topbarImage.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
    topbarImage.image = [UIImage imageNamed:@"top_bar_bg.png"];
    [topView addSubview:topbarImage];
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_bg.png"] forState:UIControlStateNormal];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    backBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [backBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    
    backBtn.titleLabel.shadowOffset = CGSizeMake(1, 1);
    backBtn.contentEdgeInsets = UIEdgeInsetsMake(3, 13, 5, 5);
    [backBtn addTarget:self action:@selector(backBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(8, 24, 50, 35);
    [topView addSubview:backBtn];
    
    titlelabel = [[UILabel alloc]initWithFrame:CGRectMake(58, 30, 220, 30)];
    titlelabel.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    titlelabel.backgroundColor = [UIColor clearColor];
    titlelabel.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:titlelabel];
    
    [titlelabel release];
    [topbarImage release];
    
    topTintLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 60, 320, 40)] autorelease];
    topTintLabel.textAlignment = UITextAlignmentCenter;
    [self.view addSubview:topTintLabel];
    
    bottomTintLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, IMAGEHIGHT - 40, 320, 40)] autorelease];
    bottomTintLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    bottomTintLabel.textAlignment = UITextAlignmentCenter;
    [self.view addSubview:bottomTintLabel];
}
-(void)backBtnClicked{

    
    NSLog(@"点击返回了  现在应该返回目录界面的了啊");
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    mWebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 60, 320, IMAGEHIGHT - 60)];
    mWebView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    mWebView.delegate = self;
    mWebView.scrollView.delegate = self;
    mWebView.backgroundColor = [UIColor clearColor];
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"ArticleHTML/article" withExtension:@"html"];
    [mWebView loadRequest:[NSURLRequest requestWithURL:url]];
    [self.view addSubview:mWebView];
    
//    NSInteger themeState = [[NSUserDefaults standardUserDefaults] integerForKey:@"themeState"];
//    mWindow  = [[UIWindow alloc]initWithFrame:CGRectMake(0, 0, 320, 20)];
//    mWindow.alpha = 0.4;
//    [self changeColorWithTag:themeState];
//    mWindow.windowLevel = UIWindowLevelStatusBar;
//    mWindow.hidden = NO;
    
    [self createCurrView];
    [self createBottomView];
    [self loadArticleAtIndex:self.currentIndex];
}
-(void)addNovleRead{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[DataRequest sharedRequest] addNovelReadInfo:self.itemID nc_id:self.idStr];
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    });
}
-(void)webViewClicked{
    [UIView animateWithDuration:0.3 animations:^{
        topView.frame = CGRectMake(0, -40, 320, 40);
        currView.frame = CGRectMake(0, IMAGEHIGHT, 320, 40);
        bottomView.frame = CGRectMake(0, IMAGEHIGHT, 320, 60);
        mWebView.frame = CGRectMake(0, 0, 320, self.view.bounds.size.height);
    }];
    
}
-(void)createCurrView{
    currView = [[UIView alloc]initWithFrame:CGRectMake(0, IMAGEHIGHT - 40, 320, 40)];
    currView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    currView.userInteractionEnabled = YES;
    [self.view addSubview:currView];
    UIImageView * currImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
    currImage.image = [UIImage imageNamed:@"tab_bg.png"];
    [currView addSubview:currImage];
//    NSArray * array = [NSArray arrayWithObjects:@"分享",@"收藏",@"评论",@"设置" ,nil];
    NSArray * array = [NSArray arrayWithObjects:@"设置" ,nil];

    UISegmentedControl * seg = [[UISegmentedControl alloc]initWithItems:array];
    seg.frame = CGRectMake(20, 5, 280, 30);
    seg.segmentedControlStyle = UISegmentedControlStyleBordered;
    seg.momentary = YES;
    [seg addTarget:self action:@selector(segClicked:) forControlEvents:UIControlEventValueChanged];
    seg.tintColor = [UIColor whiteColor];
    [currView addSubview:seg];
    [currImage release];
    [seg release];
}
-(void)createBottomView{
    bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, IMAGEHIGHT, 320, 60)];
    bottomView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin ;
    bottomView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bottomView];

    UIView * alphView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
    alphView.backgroundColor = [UIColor blackColor];
    alphView.alpha = 0.4;
    [bottomView addSubview:alphView];
    [alphView release];

    fontView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
    [bottomView addSubview:fontView];
    
    stateView = [[UIView alloc]initWithFrame:CGRectMake(0, 30, 320, 30)];
    [bottomView addSubview:stateView];
    

    for (int i = 0 ; i < 3; i ++) {
        UIButton * button = [self createButtonWithFrame:CGRectMake(70 + i * 60, 2, 60, 25) tag:101 + i image:[UIImage imageNamed:[NSString stringWithFormat:@"font%d_bg.png",i + 1]] highlightImage:[UIImage imageNamed:[NSString stringWithFormat:@"font%d_bg_selected.png",i + 1]] action:@selector(topBtnClicked:)];
        [fontView addSubview:button];
    }
    //白天 夜间  牛皮纸 护眼
    NSArray * nameArray = [NSArray arrayWithObjects:@"白天",@"夜间",@"护眼",@"牛皮纸", nil];
    NSArray * imageArray = [NSArray arrayWithObjects:@"style_day.png",@"style_dark.png",@"style_old.png",@"style_hy.png", nil];
    NSArray * selectArray = [NSArray arrayWithObjects:@"style_day_selected.png",@"style_dark_selected.png",@"style_old_selected.png",@"style_hy_selected.png", nil];
    for (int i = 0; i < 4; i ++) {
        UIButton * button = [self createButtonWithFrame:CGRectMake(30 + 65 * i, 0, 65, 30) tag:104 + i image:[UIImage imageNamed:[imageArray objectAtIndex:i]] highlightImage:[UIImage imageNamed:[selectArray objectAtIndex:i]] action:@selector(bottomBtnClicked:)];
        [button setTitle:[nameArray objectAtIndex:i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [stateView addSubview:button];
    }
    NSInteger fontSize = [[NSUserDefaults standardUserDefaults] integerForKey:@"fontState"];
    NSInteger themeState = [[NSUserDefaults standardUserDefaults] integerForKey:@"themeState"];
    if (fontSize != 0) {
        UIButton * fontBtn = (UIButton *)[self.view viewWithTag:fontSize];
        fontBtn.selected = YES;
        
    }
    if (themeState != 0) {
        UIButton * themeBtn = (UIButton *)[self.view viewWithTag:themeState];
        themeBtn.selected = YES;
    }
}
-(UIButton *)createButtonWithFrame:(CGRect)frame tag:(NSInteger)tag image:(UIImage *)image highlightImage:(UIImage *)highlightImage action:(SEL)action{
    UIButton * mButton = [UIButton buttonWithType:UIButtonTypeCustom];
    mButton.frame = frame;
    mButton.tag = tag;
    [mButton setBackgroundImage: image forState:UIControlStateNormal];
    [mButton setBackgroundImage: highlightImage forState:UIControlStateHighlighted];
    [mButton setBackgroundImage:highlightImage forState:UIControlStateSelected];
    [mButton addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    return mButton;
}
-(void)topBtnClicked:(UIButton *)button{
    for (UIButton * btn in fontView.subviews) {
        if (button == btn) {
            btn.selected = YES;
        }else{
            btn.selected = NO;
        }
    }
    [[NSUserDefaults standardUserDefaults] setInteger:button.tag forKey:@"fontState"];
    
    [mWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"changeFontSize(%d)",button.tag - 100]];
    [[NSUserDefaults standardUserDefaults] synchronize];


}
-(void)changeColorWithTag:(NSInteger)tag{
    
    [UIView animateWithDuration:0.3 animations:^{
        
        switch (tag) {
            case 0:
            {
//                mWebView.backgroundColor = [UIColor whiteColor];
                mWindow.backgroundColor = [UIColor whiteColor];
            }
                break;
            case 104:
            {
                mWindow.backgroundColor = [UIColor whiteColor];
//                mWebView.backgroundColor = [UIColor whiteColor];
            }
                break;
            case 105:
            {
                mWindow.backgroundColor = [UIColor blackColor];
//                mWebView.backgroundColor = [UIColor blackColor];
            }
                break;
            case 106:
            {
                mWindow.backgroundColor = [UIColor colorWithRed:194/255.00 green:231/255.00 blue:189/255.00 alpha:1.0];
//                mWebView.backgroundColor = [UIColor colorWithRed:194/255.00 green:231/255.00 blue:189/255.00 alpha:1.0];

            }
                break;
            case 107:
            {
                mWindow.backgroundColor = [UIColor colorWithRed:32/255.00 green:31/255.00 blue:19/255.00 alpha:1.0];
//                mWebView.backgroundColor = [UIColor colorWithRed:32/255.00 green:31/255.00 blue:19/255.00 alpha:1.0];
            }
                break;
                
            default:
                break;
        }
    }];
}
-(void)bottomBtnClicked:(UIButton *)button{
    for (UIButton * btn in stateView.subviews) {
        if (button == btn) {
            btn.selected = YES;
        }else{
            btn.selected = NO;
        }
    }
    [self changeColorWithTag:button.tag];
    [[NSUserDefaults standardUserDefaults] setInteger:button.tag forKey:@"themeState"];
    [mWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"changeTheme(%d)",button.tag - 103]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [UIView animateWithDuration:0.3 animations:^{
        bottomView.frame = CGRectMake(0, IMAGEHIGHT, 320, 60);
    }];
    
    if (scrollView == mWebView.scrollView) {
        hight = scrollView.contentOffset.y;
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.dragging == NO) {
        return;
    }
    if (scrollView == mWebView.scrollView) {
        if (scrollView.contentOffset.y > hight) {
            [self hideToolBar];
        }else{
            [self showToolBar];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.currentIndex < self.contentArray.count - 1 && scrollView.contentOffset.y > scrollView.contentSize.height - scrollView.frame.size.height + 40) {
        [self loadArticleAtIndex:self.currentIndex + 1];
    }
    else if (self.currentIndex > 0 && scrollView.contentOffset.y < -40) {
        [self loadArticleAtIndex:self.currentIndex - 1];
    }
}

- (void)hideToolBar
{
    isShowStatus = YES;
    [UIView animateWithDuration:0.3 animations:^{
        mWebView.frame = CGRectMake(0, 0, 320, self.view.bounds.size.height);
        topView.frame = CGRectMake(0, -60, 320, 60);
        currView.frame = CGRectMake(0, IMAGEHIGHT, 320, 40);
    }];
    
    if ([UIDevice currentDevice].systemVersion.floatValue<7.0) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }else{
        [self hiddenStatus];
    }
}

- (void)showToolBar
{
    isShowStatus = NO;
    [UIView animateWithDuration:0.3 animations:^{
        mWebView.frame = CGRectMake(0, 60, 320, self.view.bounds.size.height - 60);
        topView.frame = CGRectMake(0, 0, 320, 60);
        currView.frame = CGRectMake(0, IMAGEHIGHT - 40, 320, 40);
    }];
    if ([UIDevice currentDevice].systemVersion.floatValue<7.0) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    }else{
        [self hiddenStatus];
    }
}
-(void)hiddenStatus
{
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
        // iOS 7
        [self prefersStatusBarHidden];
        //        [self preferredStatusBarUpdateAnimation];
        [UIView animateWithDuration:0.5 animations:^{
            [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        }];
    }
}

-(BOOL)prefersStatusBarHidden{
    return isShowStatus;
}

-(void)segClicked:(UISegmentedControl *)seg{
    if (mWebView.scrollView.dragging) {
        return;
    }

    switch (seg.selectedSegmentIndex) {
        case 0:
        {
            [UIView animateWithDuration:0.3 animations:^{
                currView.frame = CGRectMake(0, IMAGEHIGHT, 320, 40);
                bottomView.frame = CGRectMake(0, IMAGEHIGHT - 60, 320, 60);
            }];

        }
            break;
        case 1:
        {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSDictionary * dict = [[DataRequest sharedRequest] getNovelCollectInfo:self.itemID];
                dispatch_async(dispatch_get_main_queue(), ^{
                    id message = [dict objectForKey:@"result"];
                    if ([message isKindOfClass:[NSNumber class]]) {
                        ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"收藏成功" ]autorelease];
                        [promptView show];
                    }
                    else{
                        ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"收藏失败" ]autorelease];
                        [promptView show];
                    }

                });
            });
            
        }
            break;
        case 2:
        {
        }
            break;
        case 3:
        {
//            [UIView animateWithDuration:0.3 animations:^{
//                currView.frame = CGRectMake(0, IMAGEHIGHT, 320, 40);
//                bottomView.frame = CGRectMake(0, IMAGEHIGHT - 60, 320, 60);
//            }];
        }
            break;
   
        default:
            break;
    }
}
-(void)getData{
    [self showLoadingView];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString * data = [[DataRequest sharedRequest] getNovelChapterInfo:self.idStr];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self removeloadingView];
            if (data  && [data isKindOfClass:[NSString class]]) {
                self.desStr = data;
                [self updateDisplay];
            }
        });
    });
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    [self updateDisplay];
}
- (void)updateDisplay
{
    if (_desStr && !mWebView.loading) {
        [self showToolBar];
        mWebView.scrollView.contentOffset = CGPointZero;
        NSInteger fontSize = [[NSUserDefaults standardUserDefaults] integerForKey:@"fontState"];
        NSInteger themeState = [[NSUserDefaults standardUserDefaults] integerForKey:@"themeState"];
        NSLog(@"fontSize:%d  themeState:%d",fontSize, themeState);
        [mWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"changeFontSize(%d)",fontSize - 100]];
        [mWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"changeTheme(%d)",themeState - 103]];
        [mWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"loadNovelData(%@);",_desStr]];
    }
}

- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:mWebView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
